<?php

namespace app\admin\service;

use app\admin\dao\MemberDao;
use app\admin\model\UM as UM;
use app\common\model\Member;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\ArrayUtil;
use think\exception\ValidateException;

/**
 * Class LawyerInfoService
 * @package app\admin\service
 */
class LawyerInfoService
{
    // dao
    private MemberDao $memberDao;

    public function __construct(MemberDao $memberDao)
    {
        $this->memberDao = $memberDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return Member
     */
    public function modify(UM $user, int $id, array $params): Member
    {
        $memberInfo = $params['memberInfo'] ?? [];
        if (isset($params['realname'])) {
            $memberInfo['realname'] = $params['realname'];
        }

        $params = ArrayUtil::cut($params, ['realname']);
        $memberInfo = ArrayUtil::cut($memberInfo, ['realname', 'practiceTime']);

        //这里如果要修改查询，建议把查询就放到这里
        $record = Member::field(true)
            ->with(['memberInfo'])
            ->where('id', $id)
            ->where('type', 1)
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该律师不存在或已被删除');
        }

        if (is_null($record->memberInfo)) {
            throw new ValidateException('该律师未填写律师信息，无法修改');
        }

        if ($memberInfo) {
            $record->memberInfo->save($memberInfo);
        }

        $allowField = [];
        $this->memberDao->updateActive($record, $params, $allowField);

        return $record;
    }

}
